package ws

import (
	"github.com/gorilla/websocket"
	"time"
)

func (hub *Hub) checkClientAlive(session *Session) {
	for {
		now := time.Now().Unix()
		//超时检测
		if session.HeartBeatTime == 0 {
			session.HeartBeatTime = now

		} else {
			if now-session.HeartBeatTime < hub.HeartBeatTimeOut {
				//没有超时，啥也不干
				// 有可能是因为前台有消息刷新了心跳时间，这样就不用再检测了
			} else {
				//检测是不是已经需要Kill掉这个Session
				if now-session.HeartBeatTime > hub.HeartBeatTimeKill {
					//结束这个线程
					session.Closer <- 1
					return
				}
				session.Locker.Lock()
				errWrite := session.Conn.WriteMessage(websocket.TextMessage,
					[]byte("ping"))
				session.Locker.Unlock()
				if hub.handleErr(errWrite) {
					session.Closer <- 1
					return
				}
			}
		}
		time.Sleep(time.Duration(hub.HeartBeatInterval) * time.Second)
	}
}
